﻿Module Module1
  Const cSET As String = "SET"
  Const cGET As String = "GET"
  Const cDEL As String = "DEL"
  Const cPSET As String = "PSET"
  Const cPGET As String = "PGET"
  Const cPDEL As String = "PDEL"
  Const cDBDEL As String = "DBDEL"
  Const cDBGET As String = "DBGET"
  Const cCON As String = "CON"
  Const cLCON As String = "LCON"
  Const cCLOSE As String = "CLOSE"
  Const cCLS As String = "CLS"
  Const cSTATE As String = "STATE"
  Const cDBCREATE As String = "DBCREATE"
  Const cDBLIST As String = "DBLIST"
  Const cLIST As String = "LIST"
  Const cPLIST As String = "PLIST"
  Const cHELP As String = "HELP"

  Const cUSER As String = "USER"
  Const cPASS As String = "PASS"
  Const cSERVICE As String = "SERVICE"
  Const cAUTH As String = "AUTH"
  Const cREVOKE As String = "REVOKE"

  Private ReadOnly Commands As List(Of String) = {cHELP,
                                                  cCLS,
                                                  cUSER,
                                                  cPASS,
                                                  cAUTH,
                                                  cREVOKE,
                                                  cSTATE,
                                                  cLIST,
                                                  cDBLIST,
                                                  cPLIST,
                                                  cGET,
                                                  cDBGET,
                                                  cPGET,
                                                  cSET,
                                                  cDBCREATE,
                                                  cPSET,
                                                  cLCON,
                                                  cCON,
                                                  cDEL,
                                                  cDBDEL,
                                                  cPDEL,
                                                  cSERVICE,
                                                  cCLOSE}.ToList

  Private sql As New SNCS.Client
  Private _stay As Boolean = True
  Private _IgnoreStayOnExit As Boolean = False
  Private _service As String = My.Settings.Service
  Private _user As String = My.Settings.User
  Private _pass As String = My.Settings.Pass

  Private _automationMode As Boolean = False

  Private Enum CtrlTypes As UInteger
    CTRL_C_EVENT = 0
    CTRL_BREAK_EVENT
    CTRL_CLOSE_EVENT
    CTRL_LOGOFF_EVENT = 5
    CTRL_SHUTDOWN_EVENT
  End Enum

  Private Delegate Function ConsoleCtrlDelegate(CtrlType As CtrlTypes) As Boolean

  Private Declare Function SetConsoleCtrlHandler Lib "kernel32" (Handler As ConsoleCtrlDelegate, Add As Boolean) As Boolean

  Private _handler As ConsoleCtrlDelegate

  Private exitCode As Integer

  Private Function _Cleanup_(CtrlType As CtrlTypes) As Boolean
    Try
      sql.Close()
    Catch ex As Exception

    End Try
    Environment.Exit(exitCode)
    Return True
  End Function

  Private Sub Cleanup(ByVal data As Object, ByVal exceptionThrown As Boolean)
    Try
      sql.Close()
    Catch ex As Exception

    End Try
  End Sub

  Private Sub _Cleanup(ByVal data As Object, ByVal exceptionThrown As System.EventArgs)
    Try
      sql.Close()
    Catch ex As Exception

    End Try
  End Sub

  Function Main() As Integer
    AddHandler AppDomain.CurrentDomain.ProcessExit, AddressOf _Cleanup
    _handler = New ConsoleCtrlDelegate(AddressOf _Cleanup_)
    SetConsoleCtrlHandler(_handler, True)
    System.Runtime.CompilerServices.RuntimeHelpers.ExecuteCodeWithGuaranteedCleanup(AddressOf _Main, AddressOf Cleanup, Nothing)
    Return exitCode
  End Function


  Private comlist As New List(Of String)
  Private combuilder As New Text.StringBuilder()
  Private running As Boolean = True

  Sub _Main(ByVal data As Object)
    Dim args() As String = Environment.GetCommandLineArgs()
    Dim runWithArgs As Boolean = False
    'Console.TreatControlCAsInput = True
    Dim _command As String = String.Empty
    If args.Count = 2 Then
      _command = args(1).ToUpper
      runWithArgs = True
    ElseIf args.Count > 2 Then
      runWithArgs = True
      '_command = args(1).ToUpper
      If "true".StartsWith(args(2).ToLower.Trim) Then
        _IgnoreStayOnExit = True
        For i As Integer = 1 To args.Count - 1 Step 1
          If i <> 2 Then
            If i = 1 Then
              _command &= args(i)
            Else
              _command &= " " + args(i)
            End If
          End If
        Next
      Else
        For i As Integer = 1 To args.Count - 1 Step 1
          If i = 1 Then
            _command &= args(i)
          Else
            _command &= " " + args(i)
          End If
        Next
      End If
    Else
      _command = String.Empty
    End If
    Do While _stay
      _stay = False
      If runWithArgs Then '_command = "4as86d49egf4w65sdf13sd2f1s32f1sd" Then 'If command <> "" Then
        runWithArgs = False
        If IO.File.Exists(_command) Then
          _automationMode = True
          Using sr As New IO.StreamReader(_command, System.Text.Encoding.Default, True)
            Dim line As String = String.Empty
            Do While Not sr.EndOfStream
              line = sr.ReadLine.Trim
              If "stay".StartsWith(line.ToLower) Then
                _stay = True
                _command = "0"
              ElseIf "if".StartsWith(line.ToLower) AndAlso line.ToLower.Contains("then") Then
                Dim tmpcommand As String = line.Substring(2).Trim
                Dim cond As String = System.Text.RegularExpressions.Regex.Split(tmpcommand, "then", Text.RegularExpressions.RegexOptions.IgnoreCase)(0)
              ElseIf Not String.IsNullOrWhiteSpace(line) AndAlso Not line.StartsWith("#") Then
                Console.WriteLine("")
                If Not line.ToLower.Contains("pass") Then
                  Console.WriteLine(line.Trim)
                End If
                If "exit".StartsWith(line.ToLower) Then
                  If _IgnoreStayOnExit Then _stay = False
                  Exit Do
                End If
                If Run(line.Split("#"c)(0).Split(" "c)) <> 0 Then '.Split(" "c)
                  Exit Do
                End If
              End If
            Loop
          End Using
        Else
          Try
            exitCode = parseAndRun(_command)
            End
          Catch ex As Exception
            Console.WriteLine(ex.Message)
            Console.WriteLine(ex.StackTrace)
            End
          End Try
        End If
      Else
        Dim tmp As String = String.Empty
        Do While running
          Console.Write("Command: ") : tmp = Console.ReadLine
          comlist.Clear()
          parseAndRun(tmp)
        Loop
      End If
    Loop
    exitCode = 0
  End Sub

  Private Function parseAndRun(ByVal line As String) As Integer
    Dim result As Integer = -1
    Try
      If Not String.IsNullOrWhiteSpace(line.ToLower.Trim) Then
        If Not "exit".StartsWith(line.ToLower) Then
          If line.ToUpper.Contains("AND") Then
            For Each c As String In System.Text.RegularExpressions.Regex.Split(line.Trim, "AND", Text.RegularExpressions.RegexOptions.IgnoreCase)
              Console.WriteLine("")
              Console.WriteLine(c.Trim)
              If Not String.IsNullOrWhiteSpace(c.Trim.ToLower) AndAlso "exit".StartsWith(c.Trim.ToLower) Then
                running = False
                Exit For
              End If
              result = Run(c.Trim.Split(" "c))
              If result <> 0 Then
                Exit For
              End If
            Next
          ElseIf line.Contains("&&") Then
            For Each c As String In System.Text.RegularExpressions.Regex.Split(line.Trim, System.Text.RegularExpressions.Regex.Escape("&&"), Text.RegularExpressions.RegexOptions.IgnoreCase)
              Console.WriteLine("")
              Console.WriteLine(c.Trim)
              If Not String.IsNullOrWhiteSpace(c.Trim.ToLower) AndAlso "exit".StartsWith(c.Trim.ToLower) Then
                running = False
                Exit For
              End If
              result = Run(c.Trim.Split(" "c))
              If result <> 0 Then '.Split(" "c)
                Exit For
              End If
            Next
          Else
            result = Run(line.Trim.Split(" "c))
          End If
        Else
          running = False
        End If
      Else
        Console.WriteLine("")
      End If
    Catch ex As Exception
      Console.WriteLine(ex.Message)
      Console.WriteLine(ex.StackTrace)
    End Try
    Return result
  End Function

  Private Sub ShowHelp(ByVal Command As String)
    Select Case Command

      Case cSET
        Console.WriteLine("Syntax: {0}SET [Name] [Value]{0}", Chr(34))
        Console.WriteLine("")
      Case cGET
        Console.WriteLine("Syntax: {0}GET [Name]{0}", Chr(34))
        Console.WriteLine("")
      Case cDEL
        Console.WriteLine("Syntax: {0}DEL [Name]{0}", Chr(34))
        Console.WriteLine("")
      Case cPSET
        Console.WriteLine("Syntax: {0}PSET [Identifier] [Name] [Value]{0}", Chr(34))
        Console.WriteLine("")
      Case cPGET
        Console.WriteLine("Syntax: {0}PGET [Identifier] [Name]{0}", Chr(34))
        Console.WriteLine("")
      Case cPDEL
        Console.WriteLine("Syntax: {0}PDEL [Identifier] [Name]{0}", Chr(34))
        Console.WriteLine("")
      Case cCON
        Console.WriteLine("Remote Service:")
        Console.WriteLine("Syntax: {0}CON [ServerName or IP]{0}", Chr(34))
        Console.WriteLine("")
        Console.WriteLine("Remote Service (Different Port):")
        Console.WriteLine("Syntax: {0}CON [ServerName or IP] [Port]{0}", Chr(34))
        Console.WriteLine("")
      Case cLCON
        Console.WriteLine("Local Service:")
        Console.WriteLine("Syntax: {0}CON{0}", Chr(34))
        Console.WriteLine("")
        Console.WriteLine("Local Service (Different Port):")
        Console.WriteLine("Syntax: {0}CON [Port]{0}", Chr(34))
        Console.WriteLine("")
      Case cDBGET
        Console.WriteLine("Syntax: {0}DBGET [Identifier]{0}", Chr(34))
        Console.WriteLine("")
      Case cDBCREATE
        Console.WriteLine("Syntax: {0}DBCREATE [Identifier]{0}", Chr(34))
        Console.WriteLine("")
      Case cDBDEL
        Console.WriteLine("Syntax: {0}DBDEL [Identifier]{0}", Chr(34))
        Console.WriteLine("")
      Case cDBLIST
        Console.WriteLine("Syntax: {0}DBLIST Optional:[Identifier]{0}", Chr(34))
        Console.WriteLine("")
      Case cLIST
        Console.WriteLine("Syntax: {0}LIST Optional:[Name]{0}", Chr(34))
        Console.WriteLine("")
      Case cPLIST
        Console.WriteLine("Syntax: {0}PLIST [Identifier] Optional:[Name]{0}", Chr(34))
        Console.WriteLine("")
      Case cUSER
        Console.WriteLine("Syntax: {0}USER [Name]{0}", Chr(34))
        Console.WriteLine("")
      Case cSERVICE
        Console.WriteLine("Syntax: {0}SERVICE [Name]{0}", Chr(34))
        Console.WriteLine("")
      Case Else
        Console.WriteLine("Syntax: {0}Command {1}Argumentlist{2}{0}", Chr(34), "{", "}")
        Console.WriteLine("")
        Console.WriteLine("Commands:")
        Console.WriteLine(cUSER)
        Console.WriteLine("Sets the user for the connection")
        Console.WriteLine("")
        Console.WriteLine(cPASS)
        Console.WriteLine("Sets the password for the connection")
        Console.WriteLine("")
        Console.WriteLine(cAUTH)
        Console.WriteLine("Authenticates the session for write access")
        Console.WriteLine("")
        Console.WriteLine(cREVOKE)
        Console.WriteLine("Deauthenticates the session for write access")
        Console.WriteLine("")
        Console.WriteLine(cSERVICE)
        Console.WriteLine("Sets the service for the connection")
        Console.WriteLine("")
        Console.WriteLine(cCON)
        Console.WriteLine("Connects to a data service")
        Console.WriteLine("")
        Console.WriteLine(cLCON)
        Console.WriteLine("Connects to a local data service")
        Console.WriteLine("")
        Console.WriteLine(cCLOSE)
        Console.WriteLine("Closes the connection to a data service")
        Console.WriteLine("")

        'Console.WriteLine(cLIST)
        'Console.WriteLine("Lists all ")
        'Console.WriteLine("")
        'Console.WriteLine(cCLOSE)
        'Console.WriteLine("Closes the connection to a data service")
        'Console.WriteLine("")
        'Console.WriteLine(cCLOSE)
        'Console.WriteLine("Closes the connection to a data service")
        'Console.WriteLine("")

        Console.WriteLine(cLIST)
        Console.WriteLine("Shows a list of all keys and values")
        Console.WriteLine("")
        Console.WriteLine(cSET)
        Console.WriteLine("Sets a general value")
        Console.WriteLine("")
        Console.WriteLine(cGET)
        Console.WriteLine("Gets a general value")
        Console.WriteLine("")
        Console.WriteLine(cDEL)
        Console.WriteLine("Deletes a general value")
        Console.WriteLine("")
        Console.WriteLine(cDBLIST)
        Console.WriteLine("Shows a list of all DBs")
        Console.WriteLine("")
        Console.WriteLine(cDBGET)
        Console.WriteLine("Gets a DB with the specified identifier")
        Console.WriteLine("")
        Console.WriteLine(cDBCREATE)
        Console.WriteLine("Creates a DB with the specified identifier")
        Console.WriteLine("")
        Console.WriteLine(cDBDEL)
        Console.WriteLine("Deletes all private values with the specified identifier")
        Console.WriteLine("")
        Console.WriteLine(cPLIST)
        Console.WriteLine("Shows all private keys and values for a given DB")
        Console.WriteLine("")
        Console.WriteLine(cPSET)
        Console.WriteLine("Sets a private value")
        Console.WriteLine("")
        Console.WriteLine(cPGET)
        Console.WriteLine("Gets a private value")
        Console.WriteLine("")
        Console.WriteLine(cPDEL)
        Console.WriteLine("Deletes a private value")
        Console.WriteLine("")
        Console.WriteLine(cSTATE)
        Console.WriteLine("Shows the connection state")
        Console.WriteLine("")
        Console.WriteLine(cCLS)
        Console.WriteLine("Clears the Screen")
        Console.WriteLine("")
        Console.WriteLine("For detailed help, use the Command: {0}[CommandName]{0}", Chr(34))
        Console.WriteLine("")
        Console.WriteLine("")
    End Select
  End Sub

  Private CommandBuilder As New Text.StringBuilder
  Private _ArgList As New List(Of String)
  Private Function Run(ByVal args() As String) As Integer
    Try
      Dim _command As String = args(0).ToUpper
      Dim retval As Integer = 0
      Dim rerun As Boolean = True
      Dim showhelpnow As Boolean = False
      If Not Commands.Contains(_command) Then
        Do While rerun
          Dim shelp As Boolean = True
          If Not String.IsNullOrWhiteSpace(_command.Trim) Then
            If Commands.FirstOrDefault(Function(s As String) As Boolean
                                         Return s.StartsWith(_command)
                                       End Function) <> "" Then
              shelp = False
              For Each s As String In Commands
                If s.StartsWith(_command) Then
                  _command = s
                  Exit For
                End If
              Next
            End If
          End If
          If _command = cHELP AndAlso args.Count > 1 Then
            rerun = True
            showhelpnow = True
            _command = args(1).ToUpper
          ElseIf _command = cHELP Then
            ShowHelp(_command)
            Return 1
            Exit Function
          Else
            rerun = False
            If shelp OrElse showhelpnow Then
              ShowHelp(_command)
              Return 1
              Exit Function
            End If
          End If
        Loop
      End If

      CommandBuilder.Clear()
      _ArgList.Clear()
      If _command = cSET OrElse _command = cPGET OrElse _command = cPDEL Then
        If args.Count < 3 Then
          Console.WriteLine("Wrong Parametercount!")
          Console.WriteLine("")
          ShowHelp(_command)
          Return 1
        End If
        If args.Count > 3 Then
          For i As Integer = 2 To args.GetUpperBound(0) Step 1
            CommandBuilder.Append(args(i))
            CommandBuilder.Append(" ")
          Next

          For i As Integer = 0 To 1
            _ArgList.Add(args(i))
          Next
          _ArgList.Add(CommandBuilder.ToString.Trim)
          args = _ArgList.ToArray
        End If
      ElseIf _command = cGET Then
        If args.Count < 2 Then
          Console.WriteLine("Wrong Parametercount!")
          Console.WriteLine("")
          ShowHelp(_command)
          Return 1
        End If
        If args.Count > 2 Then
          For i As Integer = 1 To args.GetUpperBound(0) Step 1
            CommandBuilder.Append(args(i))
            CommandBuilder.Append(" ")
          Next

          For i As Integer = 0 To 0
            _ArgList.Add(args(i))
          Next
          _ArgList.Add(CommandBuilder.ToString.Trim)
          args = _ArgList.ToArray
        End If
      ElseIf _command = cPSET Then
        If args.Count < 4 Then
          Console.WriteLine("Wrong Parametercount!")
          Console.WriteLine("")
          ShowHelp(_command)
          Return 1
        End If
        If args.Count > 4 Then
          For i As Integer = 3 To args.GetUpperBound(0) Step 1
            CommandBuilder.Append(args(i))
            CommandBuilder.Append(" ")
          Next

          For i As Integer = 0 To 2
            _ArgList.Add(args(i))
          Next
          _ArgList.Add(CommandBuilder.ToString.Trim)
          args = _ArgList.ToArray
        End If
      ElseIf _command = cCON Then
        If args.Count < 2 AndAlso args.Count < 3 Then
          Console.WriteLine("Wrong Parametercount!")
          Console.WriteLine("")
          ShowHelp(_command)
          Return 1
        End If
      ElseIf _command = cLCON Then
        If args.Count < 2 AndAlso args.Count < 1 Then
          Console.WriteLine("Wrong Parametercount!")
          Console.WriteLine("")
          ShowHelp(_command)
          Return 1
        End If
      ElseIf _command = cCLOSE OrElse _command = cCLS OrElse _command = cSTATE Then
        If args.Count < 1 Then
          Console.WriteLine("Wrong Parametercount!")
          Console.WriteLine("")
          ShowHelp(_command)
          Return 1
        End If
      ElseIf _command = cDBDEL OrElse _command = cDBGET OrElse _command = cDBCREATE Then
        If args.Count < 2 Then
          Console.WriteLine("Wrong Parametercount!")
          Console.WriteLine("")
          ShowHelp(_command)
          Return 1
        End If
      ElseIf _command = cLIST OrElse _command = cDBLIST Then
        If args.Count < 1 Then
          Console.WriteLine("Wrong Parametercount!")
          Console.WriteLine("")
          ShowHelp(_command)
          Return 1
        End If
      ElseIf _command = cPLIST Then
        If args.Count < 2 Then
          Console.WriteLine("Wrong Parametercount!")
          Console.WriteLine("")
          ShowHelp(_command)
          Return 1
        End If
      ElseIf _command = cDEL Then
        If args.Count < 2 Then
          Console.WriteLine("Wrong Parametercount!")
          Console.WriteLine("")
          ShowHelp(_command)
          Return 1
        End If
      ElseIf _command = cUSER OrElse _command = cSERVICE Then
        If args.Count < 2 Then
          Console.WriteLine("Wrong Parametercount!")
          Console.WriteLine("")
          ShowHelp(_command)
          Return 1
        End If
      ElseIf _command = cPASS Then
        If _automationMode Then
          If args.Count < 2 Then
            Console.WriteLine("No Password given!")
            Console.WriteLine("")
            Return 1
          End If
        Else
          If args.Count < 1 Then
            Console.WriteLine("Wrong Parametercount!")
            Console.WriteLine("")
            ShowHelp(_command)
            Return 1
          End If
        End If
      ElseIf _command = cAUTH Then
        If args.Count < 1 Then
          Console.WriteLine("Wrong Parametercount!")
          Console.WriteLine("")
          ShowHelp(_command)
          Return 1
        End If
      ElseIf _command = cREVOKE Then
        If args.Count < 1 Then
          Console.WriteLine("Wrong Parametercount!")
          Console.WriteLine("")
          ShowHelp(_command)
          Return 1
        End If
      Else
        ShowHelp(cHELP)
        Return 1
      End If
      Dim tmp As String = String.Empty
      Select Case _command
        Case cCON
          Try
            If args.Count = 2 Then
              If sql.Connect(args(1), ServiceName:=_service) Then
                retval = 2
              Else
                retval = 3
              End If
            Else
              If sql.Connect(args(1), Integer.Parse(args(2)), ServiceName:=_service) Then
                retval = 2
              Else
                retval = 3
              End If
            End If
          Catch ex As Exception
            Console.WriteLine(ex.Message)
            retval = 3
          End Try
        Case cLCON
          Try
            If args.Count = 1 Then
              If sql.Connect(ServiceName:=_service) Then
                retval = 2
              Else
                retval = 3
              End If
            Else
              If sql.Connect("localhost", Integer.Parse(args(2)), ServiceName:=_service) Then
                retval = 2
              Else
                retval = 3
              End If
            End If
          Catch ex As Exception
            Console.WriteLine(ex.Message)
            retval = 3
          End Try
        Case cCLOSE
          sql.Close()
          retval = 5
        Case cSET
          If sql.SetValue(args(1), args(2)) Then
            retval = 0
          Else
            retval = 1
          End If
        Case cGET
          tmp = sql.GetValue(args(1))
          If String.IsNullOrWhiteSpace(tmp) Then
            retval = 1
          Else
            Console.WriteLine("Result: {0}", tmp)
            retval = 0
          End If
        Case cDEL
          If sql.DelValue(args(1)) Then
            retval = 0
          Else
            retval = 1
          End If
        Case cPSET
          If sql.SetPrivateValue(sql.GetDB(args(1), False), args(2), args(3)) Then
            retval = 0
          Else
            retval = 1
          End If
        Case cPGET
          tmp = sql.GetPrivateValue(sql.GetDB(args(1), False), args(2))
          If String.IsNullOrWhiteSpace(tmp) Then
            retval = 1
          Else
            Console.WriteLine("Result: {0}", tmp)
            retval = 0
          End If
        Case cPDEL
          If sql.DelPrivateValue(sql.GetDB(args(1)), args(2)) Then
            retval = 0
          Else
            retval = 1
          End If
        Case cDBDEL
          If sql.DeleteDB(args(1)) Then
            retval = 0
          Else
            retval = 1
          End If
        Case cDBGET
          tmp = sql.GetDB(args(1), False)
          If Not String.IsNullOrWhiteSpace(tmp) Then
            retval = 6
          Else
            retval = 1
          End If
        Case cDBCREATE
          tmp = sql.GetDB(args(1))
          If Not String.IsNullOrWhiteSpace(tmp) Then
            retval = 4
          Else
            retval = 1
          End If
        Case cCLS
          Console.Clear()
          retval = -1
        Case cSTATE
          Console.WriteLine("Connected with {0}:{1}", sql.ConnectedServer, sql.ConnectedServerPort.ToString)
          Console.WriteLine("")
          retval = -1
        Case cLIST
          Console.WriteLine("")
          Dim result As Dictionary(Of String, String)
          If args.Count < 2 Then
            result = sql.ListValues()
          Else
            result = sql.ListValues(args(1))
          End If
          If result Is Nothing Then
            retval = 1
          Else
            For Each kv As KeyValuePair(Of String, String) In result
              Console.WriteLine("{0} = {1}", kv.Key, kv.Value)
            Next
            retval = -1
          End If
          Console.WriteLine("")
          retval = -1
        Case cPLIST
          Console.WriteLine("")
          Dim result As Dictionary(Of String, String)
          If args.Count < 3 Then
            result = sql.ListPrivateValues(sql.GetDB(args(1), False))
          Else
            result = sql.ListPrivateValues(sql.GetDB(args(1), False), args(2))
          End If
          If result Is Nothing Then
            retval = 1
          Else
            For Each kv As KeyValuePair(Of String, String) In result
              Console.WriteLine("{0} = {1}", kv.Key, kv.Value)
            Next
            retval = -1
          End If
          Console.WriteLine("")
        Case cDBLIST
          Console.WriteLine("")
          Dim result As List(Of String)
          If args.Count < 2 Then
            result = sql.ListDBs
          Else
            result = sql.ListDBs(args(1))
          End If
          If result Is Nothing Then
            retval = 1
          Else
            For Each s As String In result
              Console.WriteLine(s)
            Next
            retval = -1
          End If
          Console.WriteLine("")
        Case cUSER
          Console.WriteLine("")
          _user = args(1)
          retval = -1
        Case cAUTH
          Console.WriteLine("")
          sql.Authenticate(_user, _pass)
          retval = 7
        Case cREVOKE
          Console.WriteLine("")
          sql.Revoke()
          retval = 8
        Case cSERVICE
          Console.WriteLine("")
          _service = args(1)
          retval = -1
        Case cPASS
          If _automationMode Then
            Console.WriteLine("")
            _pass = args(1)
          Else
            Console.WriteLine("")
            Console.WriteLine("Please enter password:")
            Dim oldColor As System.ConsoleColor = Console.ForegroundColor
            Try
              Console.ForegroundColor = Console.BackgroundColor
              _pass = Console.ReadLine()
            Finally
              Console.ForegroundColor = oldColor
            End Try
          End If
          retval = -1
      End Select
      Select Case retval
        Case 0
          Console.WriteLine("Query successful!")
          Console.WriteLine("")
        Case -1
          retval = 0
        Case 2
          Console.WriteLine("Connection established!")
          Console.WriteLine("")
          retval = 0
        Case 3
          Console.WriteLine("Connection error!")
          Console.WriteLine("")
        Case 4
          Console.WriteLine("DB created | Query successful!")
          Console.WriteLine("")
          Console.WriteLine("ID: {0}", tmp)
          Console.WriteLine("")
          retval = 0
        Case 5
          Console.WriteLine("Connection closed!")
          Console.WriteLine("")
          retval = 0
        Case 6
          Console.WriteLine("DB found | Query successful!")
          Console.WriteLine("")
          Console.WriteLine("ID: {0}", tmp)
          Console.WriteLine("")
        Case 7
          Console.WriteLine("Authentication successful!")
          Console.WriteLine("")
          retval = 0
        Case 8
          Console.WriteLine("Authentication revoked!")
          Console.WriteLine("")
          retval = 0
        Case Else
          Console.WriteLine("Query failed!")
          Console.WriteLine("")
      End Select
      Return retval
    Catch ex As Auxiliary.AuthenticationException
      Console.WriteLine(ex.Message)
      Console.WriteLine("")
      Return -99999
    Catch ex As Exception
      Console.WriteLine("Not connected!")
      Console.WriteLine("")
      Return -99999
    End Try
  End Function
End Module
